import { uploadFile } from "../../utils/request";
import { IMAGAE_BASE_URL } from "../../constants/api";

Component({
  properties: {
    list: {
      type: Array,
      value: [],
    },
    max: {
      type: Number,
      value: 5,
    },
  },
  lifetimes: {
    ready() {
      const array = this.properties.list.map((item) => ({
        url: `${IMAGAE_BASE_URL}${item.url}`,
        value: item.url,
        type: "image",
        removeBtn: true,
      }));
      console.log("xxxxxxxxattached", array);
      this.setData({
        fileList: array,
        maxCount: this.properties.max,
      });
    },
  },
  data: {
    maxCount: 5,
    fileList: [],
    // [
    // {
    //   url: "https://tdesign.gtimg.com/mobile/demos/example4.png",
    //   id: "xxx",
    //   value: "uploaded1.png",
    //   type: "image",
    //   documentId: 'xx',
    //   removeBtn: true,
    // },
    // ],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
  },
  methods: {
    async handleAdd(e) {
      const { fileList } = this.data;
      const { files } = e.detail;
      // console.log("===handleAdd====", files, e.detail);
      const newFile = files[0];
      try {
        const fileInfo = await uploadFile(newFile.url);
        if (fileInfo) {
          // newFile.status = undefined;
          console.log("===fileInfo====", fileInfo.url);
          newFile.value = fileInfo.url;
        } else {
          newFile.status = "failed";
        }
      } catch (error) {
        console.error("上传失败", error);
        newFile.status = "failed";
      }
      newFile.removeBtn = true;
      this.setFileList([...fileList, newFile]);
    },
    handleRemove(e) {
      const { index } = e.detail;
      const { fileList } = this.data;
      console.log("===handleRemove====", index);
      fileList.splice(index, 1);
      this.setFileList(fileList);
    },
    handleDrop(e) {
      const { files } = e.detail;
      console.log("===handleDrop====", e.detail);
      this.setFileList(files);
    },
    setFileList(files) {
      this.setData({
        fileList: files,
      });
      this.triggerEvent("change", this.data.fileList);
    },
  },
});
